package com.sea.base.ext.view

import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.text.Editable
import android.text.InputFilter
import android.text.TextUtils
import android.text.TextWatcher
import android.util.TypedValue
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
import androidx.core.widget.TextViewCompat
import androidx.core.widget.addTextChangedListener
import com.sea.base.ext.global.formatToEllipsize
import com.sea.base.ext.global.getOrNull

@Suppress("NOTHING_TO_INLINE")
inline fun TextView.setTextColorRes(@ColorRes resId: Int) {
    setTextColor(ContextCompat.getColor(context, resId))
}

/**
 * 设置text
 * null为空字符串
 */
fun TextView.setTextString(obj: Any?) {
    text = when (obj) {
        is StringBuilder, is StringBuffer -> {
            obj.toString()
        }

        null, "null", "Null", "NULL" -> {
            ""
        }

        is CharSequence -> {
            obj
        }

        else -> {
            obj.toString()
        }
    }
}

/**
 * 方便代码统一用屏幕比例：
 * textSizePx = 14.screenRatio
 */
inline var TextView.textSizePx: Int
    set(value) {
        setTextSize(TypedValue.COMPLEX_UNIT_PX, value.toFloat())
    }
    get() = textSize.toInt()

/**
 * 设置字体加粗，和xml效果一致
 * 注意：之前版本“Typeface.create(typeface, Typeface.BOLD)”有细微bug（部分手机加粗效果不一致、无法取消加粗）
 *       暂时直接设置成默认字体样式，如果后期有用到自定义字体，则这里需要调整
 */
inline var TextView.isTextBold: Boolean
    set(value) {
        if (value) {
            setTypeface(Typeface.DEFAULT_BOLD, Typeface.NORMAL)
        } else {
            setTypeface(Typeface.DEFAULT, Typeface.NORMAL)
        }
        invalidate()
    }
    get() = typeface?.isBold ?: false

/**
 * CompoundDrawable默认缺省
 */
@Suppress("NOTHING_TO_INLINE")
inline fun TextView.setCompoundDrawablesWIB(
    left: Drawable? = null,
    top: Drawable? = null,
    right: Drawable? = null,
    bottom: Drawable? = null
) {
    setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom)
}

@Suppress("NOTHING_TO_INLINE")
inline fun TextView.setCompoundDrawablesWIB(
    @DrawableRes left: Int = 0,
    @DrawableRes top: Int = 0,
    @DrawableRes right: Int = 0,
    @DrawableRes bottom: Int = 0
) {
    setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom)
}

inline var TextView.compoundDrawableTintListExt: ColorStateList?
    get() = TextViewCompat.getCompoundDrawableTintList(this)
    set(value) {
        TextViewCompat.setCompoundDrawableTintList(this, value)
    }

@get:ColorInt
@setparam:ColorInt
@set:ColorInt//错误的警告
inline var TextView.compoundDrawableTintColorExt: Int?
    get() = TextViewCompat.getCompoundDrawableTintList(this)?.defaultColor
    set(value) {
        TextViewCompat.setCompoundDrawableTintList(this, value?.let { ColorStateList.valueOf(it) })
    }

@get:ColorInt
@setparam:ColorInt
@set:ColorInt//错误的警告
inline var TextView.backgroundTintColorExt: Int?
    get() = backgroundTintList?.defaultColor
    set(value) {
        backgroundTintList = value?.let { ColorStateList.valueOf(it) }
    }

/**
 * 超出指定长度加…（解决maxLength无法…的问题）
 * @param newMaxLength 不包括“…”，所以实际长度会+1
 * @param newEllipsize 目前只支持START,MIDDLE,END
 */
@SuppressLint("SetTextI18n")//text拼接警告
fun TextView.setTextEllipsize(
    st: String?,
    newMaxLength: Int,
    newEllipsize: TextUtils.TruncateAt
) {
    ellipsize = null
    if (maxLength < newMaxLength + 1) {
        maxLength = newMaxLength + 1
    }
    val newSt = st?.formatToEllipsize(newMaxLength, newEllipsize)
    text = newSt
}

/**
 * 获取maxLength
 */
var TextView.maxLength: Int
    set(value) {
        val oldMaxLength =
            (filters.getOrNull { it is InputFilter.LengthFilter } as? InputFilter.LengthFilter)?.max
        if (oldMaxLength == value) {
            return
        }

        filters = (filters.filter { it !is InputFilter.LengthFilter } + InputFilter.LengthFilter(value)).toTypedArray()
    }
    get() {
        filters.forEach {
            if (it is InputFilter.LengthFilter) {
                return it.max
            }
        }
        return Int.MAX_VALUE
    }

/**
 * 可多次调用，每次都删除上一个然后添加新的
 */
inline fun TextView.addTextChangedSingleListener(
    crossinline afterTextChanged: (text: Editable?) -> Unit
): TextWatcher {
    val tagId = com.sea.base.R.id.tag_text_changed_listener
    getTypeTag<TextWatcher>(tagId)?.let {
        removeTextChangedListener(it)
    }
    val listener = addTextChangedListener(afterTextChanged = afterTextChanged)
    setTag(tagId, listener)
    return listener
}